import datetime
import os
import logging

from bookservice import BookService

from models import *
from google.appengine.ext import db
from google.appengine.api import users

class BookOwnershipService:
	def getBooksForOwner(self,owner):
		logging.info("Getting books for user %s", owner)
#		books = db.GqlQuery("SELECT * FROM BookOwnership WHERE owner = :1 ORDER BY book LIMIT 100",owner).fetch(100)
		books = owner.books.fetch(100)
		#books = BookOwnership.gql("WHERE owner = :owner",owner).fetch(100)
		#books = db.GqlQuery("SELECT * FROM BookOwnership ORDER BY book LIMIT 100").fetch(100)
		logging.info("Found %d books for user %s", len(books), owner)
		return books

	def createBookOwnership(self, _owner, _name, _author, _isbn):
		_book = BookService().getBookForISBN(_isbn)
		if (not _book):
			logging.info("Book does not yet exist. Creating %s",_isbn)
			_book = BookService().createBook(_name, _author, _isbn)
		else:
			logging.info("Book already exists %s",_isbn)
		bookOwnership = BookOwnership(book = _book, owner = _owner)
		bookOwnership.put()
		return bookOwnership	
	
	def getBookOwnership(self, _owner, _book):
		#books = db.GqlQuery("SELECT * FROM BookOwnership")
		#for book in books:
		#	logging.info("Book exists: %s",book)
		logging.info("Getting the book ownership for %s and book %s",_owner,_book)
		bookOwnership = _owner.books.filter("book = ",_book).get()
		#bookOwnership = BookOwnership.gql("WHERE owner = :1 and book = :2",_owner,_book).get()
		#bookOwnership = db.GqlQuery("SELECT * FROM BookOwnership WHERE owner = :1 and book = :2", _owner.key(),_book.key()).get()
		if (not bookOwnership):
			logging.info("Could not find the book ownership for %s and book %s",_owner,_book)
		return bookOwnership
		
	def clear(self):
		books = db.GqlQuery("SELECT * FROM BookOwnership")
		for book in books:
			book.delete()